package org.aeon.server.handler.Inbound;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.aeon.entity.User;
import org.aeon.entity.UserRelation;
import org.aeon.entity.dto.UserInfoDto;
import org.aeon.message.request.UserInfoRequestMessage;
import org.aeon.message.response.UserInfoResponseMessage;
import org.aeon.service.factory.SessionFactory;
import org.aeon.service.factory.UserRelationServiceFactory;
import org.aeon.service.factory.UserServiceFactory;
import org.modelmapper.ModelMapper;

/**
 * @author: MissingAeon
 * @date: 2024/2/23 11:35
 * @description:
 */
@Slf4j
@ChannelHandler.Sharable
public class UserInfoRequestHandler extends SimpleChannelInboundHandler<UserInfoRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, UserInfoRequestMessage msg) throws Exception {
        final UserInfoResponseMessage resMsg = new UserInfoResponseMessage();
        resMsg.setResponseID(msg.getUid());

        final Long userId = SessionFactory.getSession().getUserId(ctx.channel());
        final User user = UserServiceFactory.getService().getUserById(msg.getUserId());
        if (user != null) {
            final UserInfoDto userInfo = new ModelMapper().map(user, UserInfoDto.class);
            final UserRelation relation = UserRelationServiceFactory.getService().queryRelation(userId, userInfo.getId());
            if (relation != null) {
                userInfo.setRelation(relation.getIsFriend());
            }
            resMsg.setResponse(true, "信息获取成功");
            resMsg.setUser(userInfo);
        } else resMsg.setResponse(false, "目标id不存在");
        ctx.writeAndFlush(resMsg);
    }
}
